import { Prisma } from '@prisma/client';
import prisma from '@/server/lib/prisma';
import { verifyToken } from '@/server/lib/jwt';

export default defineEventHandler(async (event) => {
  try {
    const where: Prisma.sys_menuWhereInput = {
      visible: '1'
    };
    const headers = getHeaders(event);
    const authorization = headers['authorization'] as string;
    const token = authorization.split(' ')[1];
    const decoded: any = verifyToken(token);
    const username = decoded.username;
    const user = await prisma.sys_user.findFirst({
      where: {
        userName: username
      },
      include: {
        roles: true
      }
    })
    if (user && user.roles && Array.isArray(user.roles)) {
      const ids: number[] = [];
      user.roles.forEach((item) => {
        ids.push(item.roleId);
      })
      const menu = await prisma.sys_role_menu.findMany({
        where: {
          roleId: {
            in: ids
          }
        },
        select: {
          menuId: true
        }
      })
      const menuIds: number[] = [];
      menu.forEach((item) => {
        menuIds.push(item.menuId);
      })
      where.menuId = {
        in: menuIds
      }
    }
    
    const result = await prisma.sys_menu.findMany({
      orderBy: {
        orderNum: 'asc'
      },
      where: where,
    })
    const datas: any = [];
    result.forEach((item) => {
      datas.push({
        menuId: item.menuId,
        parentId: item.parentId,
        path: '/admin' + item.url,
        name: item.menuName,
        meta: {
          title: item.menuName,
          en_title: item.menuEnName,
          icon: item.icon,
        },
        children: [],
      })
    })

    return {
      code: 200,
      data: datas,
    }
  } catch (e) {
    throw e;
  } finally {
    prisma.$disconnect();
  }
})